'''
https://leetcode.cn/problems/count-the-number-of-fair-pairs
'''
import bisect
from typing import List


class Solution:
    def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
        n = len(nums)
        nums.sort()
        res = 0
        for i in range(n):
            # >= 的最左位置
            a = bisect.bisect_left(nums, lower-nums[i], i+1)
            # >  的最左位置
            b = bisect.bisect_right(nums, upper-nums[i], i+1)
            res += b - a
        return res